package com.keeley.mybatisTools.controller;

import ch.qos.logback.core.util.FileUtil;
import com.jfinal.core.Controller;
import com.jfinal.kit.FileKit;
import com.jfinal.log.Logger;
import com.keeley.mybatisTools.context.GrenertorContext;
import com.keeley.mybatisTools.core.ConfigBean;
import com.keeley.mybatisTools.ext.GenerCallback;
import org.apache.commons.io.FileUtils;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.ext.jfinal.BeetlRenderFactory;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.exception.InvalidConfigurationException;
import org.mybatis.generator.exception.XMLParserException;
import org.mybatis.generator.internal.DefaultShellCallback;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by djei on 2015-02-12.
 */
public class DataBaseController extends Controller {
    private static Logger logger = Logger.getLogger(DataBaseController.class);
    private ConfigBean configBean;
    private String configXmlStr;
    private Map<String,Object> map;
    public void generate(){
        map = new HashMap<String, Object>();
        configBean =getModel(ConfigBean.class);
        logger.info(configBean.getBeanName());
        deleteFile();
        generateFile();
        try {
            buildFile();
            readFile();
            System.out.println("generate success");
            renderJson(map);
        } catch (IOException ioe) {
            ioe.printStackTrace();
            map.put("errMsg",ioe.getMessage());
            map.put("flag",true);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("errMsg",e.getMessage());
            map.put("flag",true);

        }
        renderJson(map);

    }
    public void down(){
        String path = getPara("path");
        renderFile(new File(GrenertorContext.FILE_DIR,path));
    }
    private void generateFile(){
        String temp ="/templates/generatorConfig.txt";
        if(configBean.getBuild_type()==1)
            temp ="/templates/generatorConfigSup.txt";

        logger.info(temp);
        GroupTemplate groupTemplate = BeetlRenderFactory.groupTemplate ;
        Template t =groupTemplate.getTemplate(temp);
        t.binding("config",configBean);
        configXmlStr = t.render();
    }
    private void buildFile() throws IOException, XMLParserException, SQLException, InterruptedException, InvalidConfigurationException {
        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config =cp.parseConfiguration(new StringReader(configXmlStr));
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        myBatisGenerator.generate(new GenerCallback());
    }
    private void deleteFile(){
        String xmlFilePath=replaceUrl(configBean.getMappingUrl())+configBean.getBeanName()+GrenertorContext.MAPPING_EXT;
        File xmlFile = new File(GrenertorContext.FILE_DIR,xmlFilePath);
        if(xmlFile.exists()){
            logger.info("delete "+xmlFilePath);
            xmlFile.delete();
        }

    }
    private void readFile() throws IOException {
        String beanName =configBean.getBeanName();

        String modelFilePath=replaceUrl(configBean.getModelUrl())+beanName+GrenertorContext.MODEL_EXT;
        String xmlFilePath=replaceUrl(configBean.getMappingUrl())+beanName+GrenertorContext.MAPPING_EXT;
        String mapperFilePath=replaceUrl(configBean.getMapperUrl())+beanName+GrenertorContext.MAPPER_EXT;;
        String exampleFilePath=replaceUrl(configBean.getModelUrl())+beanName+ GrenertorContext.EXAMPLE_EXT;

        String modelText=FileUtils.readFileToString(new File(GrenertorContext.FILE_DIR,modelFilePath));
        String xmlText=FileUtils.readFileToString(new File(GrenertorContext.FILE_DIR,xmlFilePath),GrenertorContext.READ_CHARSET);
        String mapperText=FileUtils.readFileToString(new File(GrenertorContext.FILE_DIR,mapperFilePath));
        String exampleText=FileUtils.readFileToString(new File(GrenertorContext.FILE_DIR,exampleFilePath));

        map.put("modelUrl",modelFilePath);
        map.put("xmlUrl",xmlFilePath);
        map.put("mapperUrl",mapperFilePath);
        map.put("exampleUrl",exampleFilePath);

        map.put("modelText",modelText);
        map.put("xmlText",xmlText);
        map.put("mapperText",mapperText);
        map.put("exampleText",exampleText);


        map.put("flag",false);

    }
    private String replaceUrl(String url){
        return File.separator+url.replace(".",File.separator)+File.separator;
    }
    public void index(){
        setAttr("root_dir",GrenertorContext.FILE_DIR);
    }
}
